#!/core/db_control.py
# This file is used for accessing database
# Author : Ismail Sunni/@ismailsunni
# Created : 2012-03-23

import MySQLdb
import util as util

class db_conn:
	'''A class for controlling database connection.'''
	
	def __init__(self, db_host, db_user, db_password, db_name):
		'''Initiate a db_conn class.'''

		self.conn = MySQLdb.connect(db_host, db_user, db_password, db_name)
		self.cursor = self.conn.cursor()

	def read(self, query):
		'''Read database.'''

		try:
			self.cursor.execute(query)
			retval = self.cursor.fetchall()

			return retval

		except Exception, e:
			util.debug('db_control.read error : ' + str(e))
			self.conn.rollback()

			return None

	def insert(self, query):
		'''Insert to database.'''

		try:
			self.cursor.execute(query)
			self.conn.commit()

			return True

		except Exception, e:
			util.debug('db_control.insert error: ' + str(e))
			self.conn.rollback()

			return False

	def delete(self, query):
		'''Delete row(s) in database.'''

		try:
			self.cursor.execute(query)
			self.conn.commit()

			return True

		except Exception, e:
			util.debug('db_control.delete error : ' + str(e))
			self.conn.rollback()
		
			return False

	def update(self, query):
		'''Update database.'''

		try:
			self.cursor.execute(query)
			self.conn.commit()

			return True

		except Exception, e:
			util.debug('db_control.update error : ' + str(e))
			self.conn.rollback()
		
			return False


def main():
	pass

if __name__ == '__main__':
	main()
